package com.zxp.server.service;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
@PropertySource("classpath:application.yml")
public class FileService {

    /*private final static String FILE_STORE_PATH = "D:\\filestore\\";*/

    @Value("${filepath}")
    private   String FILE_STORE_PATH;

    private final static String FILE_SERVICE_PATH = "file/getFile";

    @PostConstruct
    void initPath(){
        File store = new File(FILE_STORE_PATH);
        if (!store.exists() && !store.isDirectory()) {
            store.mkdirs();
        }
    }


    public String SaveFile(MultipartFile multipartFile) throws IOException {
        File file = MultipartFileToFile(multipartFile);
        String fileName = file.getName();
        InputStream fileInputStream = null;
        OutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            fileOutputStream = new FileOutputStream(FILE_STORE_PATH + fileName);
            BufferedInputStream bufferedIn = new BufferedInputStream(fileInputStream);
            BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOutputStream);
            int temp;
            while((temp=bufferedIn.read()) != -1) {
                bufferedOut.write(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fileOutputStream.close();
            fileInputStream.close();
        }
        return getAddress()+fileName;
    }

    public void getFile(String fileName, HttpServletResponse res) throws IOException {
        InputStream fileInputStream = null;
        OutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(FILE_STORE_PATH+fileName);
            fileOutputStream = res.getOutputStream();
            byte[] b=new byte[1024];  //创建数据缓冲区
            int length;
            while((length=fileInputStream.read(b))>0){  //把文件流写到缓冲区里
                fileOutputStream.write(b,0,length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fileInputStream.close();
            fileOutputStream.close();
        }
    }

    /**
     * 将MultipartFile转换为File
     *
     * @param multiFile
     * @return
     */
    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        assert fileName != null;
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile("file_", prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Value("${server.port}")
    public  String port;

    public  String getAddress() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://" + address.getHostAddress() + ":" + port +"/" + FILE_SERVICE_PATH + "/";
    }

}
